<?php

namespace App\Jobs;

use App\Models\DownloadJob;
use App\Models\Project;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use Symfony\Component\Process\Process;

class DealExcelByPython implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $projectId;
    protected $downloadId;
    protected $dirStorage;
    protected $storagePath;
    protected $type;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($projectId, $downloadId, $dirStorage, $type)
    {
        $this->projectId   = $projectId;
        $this->downloadId  = $downloadId;
        $this->dirStorage  = $dirStorage;
        $this->type        = $type;
        $this->storagePath = storage_path('app/public/') . $dirStorage; //在队列里面这里有些不同，必须使用绝对路径
    }

    /**
     * Execute the job.
     *
     * @throws Exception
     * @throws WriterException
     * @author: lxk
     * @date: 2024-12-09 14:08
     */
    public function handle()
    {
        $combinationId = Project::query()->where('id', $this->projectId)->value('combination_id');
        if ($this->type == 1) { //导出卷内目录
            if ($combinationId == 2) {
                if (in_array($this->projectId, [5,15,16])) { //京石公司8号文专用
                    $pythonScript = 'python_script/8_catalog_js.py';
                }
            } else {
                $pythonScript = match ($combinationId) {
                    1 => 'python_script/29_catalog.py',
                    2 => 'python_script/8_catalog.py',
                    3 => 'python_script/ly_catalog.py',
                    4 => 'python_script/bz_29_catalog.py',
                    default => 'python_script/common_catalog.py',
                };
            }
        } else { //导出全引目录
            $pythonScript = match ($this->projectId) {
                5 => 'python_script/czy_index.py',  // 成资渝
                default => 'python_script/common_index.py', // 普通
            };
        }
        // $process = new Process(['/www/server/pyporject_evn/versions/3.10.16/bin/python3', $pythonScript, 'storage/' . $dir, 3000]); //交给python进行合成
        $process = new Process(['D:\Python\python.exe', 'public/'.$pythonScript, 'storage/' . $this->dirStorage, 3000]); //交给python进行合成
        $process->setTimeout(1800); //python脚本执行超时时间秒
        $process->run();
        if (!$process->isSuccessful()) {
            info('python处理excel失败---' . $process->getErrorOutput());
            DownloadJob::query()->where('id', $this->downloadId)->update(['status' => 4]);
        } else {
            $downloadDir = $process->getOutput();
            $downloadDir = preg_replace("/\r?\n/", "", $downloadDir); //去掉可能的换行符 如 \n
            DownloadJob::query()->where('id', $this->downloadId)->update(['status' => 3, 'download_url' => config('site.domain') . $downloadDir]);
        }
    }

    /**
     * 任务失败
     *
     * @param \Throwable $exception
     * @author: lxk
     * @date: 2024-12-09 15:27
     */
    public function fail(\Throwable $exception)
    {
        info('---------出错了---------');
        info($exception->getMessage());
        DownloadJob::query()->where('id', $this->downloadId)->update(['status' => 4]);
    }

}
